package com.z2f.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;

import java.util.Date;

public class TokenUtils {
    public static void main(String[] args) {
        //生成token
        //链式编程
        String token = JWT.create()
                .withAudience("user001")            //账号
                .withIssuedAt(new Date())           //起始时间
                .withExpiresAt(new Date())          //过期时间
                .sign(Algorithm.HMAC256("123456")); //签名
        System.out.println(token);

        //解码
        //获得账号
        String userId = JWT.decode(token).getAudience().get(0);
        System.out.println(userId);
        //获得时间
        Date issuedAt = JWT.decode(token).getIssuedAt();
        Date expiresAt = JWT.decode(token).getExpiresAt();
        System.out.println(issuedAt + "--" + expiresAt);
        //获得签名(密码)
        String sign = JWT.decode(token).getSignature();
        System.out.println(sign);
    }

    public static String createToken(String userId,String password){
        //生成token
        //链式编程
        long times = System.currentTimeMillis();
        times += 60 * 1000 * 1;             //过期时间30分钟
        String token = JWT.create()
                .withAudience(userId)               //账号
                .sign(Algorithm.HMAC256(password)); //签名
        return token;
    }

    public static String getUserIdFromToken(String token){
        //解码
        //获得账号
        String userId = "";
        try {
            userId = JWT.decode(token).getAudience().get(0);
        }catch (Exception e){
            return null;
        }

        return userId;
    }

//    public static Boolean judgeTimeExpired(String token){
//        //解码
//        //获得账号
//        Date timeExpired = JWT.decode(token).getExpiresAt();
//
//        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String nowTimeStr = sf.format(new Date());
//        Date nowTime = null;
//        try {
//            nowTime = sf.parse(nowTimeStr);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//
//        long timeExpiredLong = timeExpired.getTime(); // 过期时间戳
//        long nowTimeLong = nowTime.getTime();         // 当前时间戳
//
//        if(timeExpiredLong > nowTimeLong){
//            return true;
//        }else{
//            return false;
//        }
//    }

    public static Boolean checkToken(String token,String acc,String psw){
        //解码
        //获得账号
        String userId = JWT.decode(token).getAudience().get(0);
        System.out.println(userId);
        return true;
    }
}
